const router = require('koa-router')()
const util = require('../utils/util')
const Menu = require('../models/menuSchema')
router.prefix('/menu')

router.get('/list',async(ctx)=>{
  const {menuName,menuState} = ctx.query
  const params = {}
  if(menuState) params.menuState = menuState
  if(menuName) params.menuName = menuName
  const res = await Menu.find(params)||[]
  const permission =getTreeMenu(res,null,[])
  ctx.body=util.success(permission)
})

function getTreeMenu(res,id,list){
  for(let i=0; i<res.length;i++){
    let item = res[i]
    if(String(item.parentId.slice().pop())==String(id)){
      list.push(item._doc)
    }
  }
  list.map(item=>{
    item.children=[]
    getTreeMenu(res,item._id,item.children)
    if(item.children.length==0){
     delete item.children 
    }else if(item.children.length>0&&item.children[0].menuType==2){
      item.action =item.children
    }
  })
    return list;
}

router.post('/operate',async(ctx)=>{
  const {_id,action,...params} = ctx.request.body
  let res,info
  try{
    if(action=='add'){
      res = await  Menu.create(params)
      info='创建成功'
    }else if(action=='edit'){
      params.updateTime = new Date()
      await Menu.findByIdAndUpdate(_id,params)
      info='编辑成功'
    }else{
      await Menu.findByIdAndRemove(_id)
      await Menu.deleteMany({ parentId: { $all: [_id] } })
      info='删除成功'
    }
    ctx.body = util.success({},info)
  }catch(error){
    
  }
})

module.exports = router